package com.wangzhou.common.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库工具类
 * 
 * 单例模式
 * @author zjx
 *
 */
public class DbUtil
{
	private String driver = ConstatFinalUtil.SYS_BUNDLE.getString("jdbc.driver") ;
	private String url = ConstatFinalUtil.SYS_BUNDLE.getString("jdbc.url") ; 
	private String user = ConstatFinalUtil.SYS_BUNDLE.getString("jdbc.user") ; 
	private String password = ConstatFinalUtil.SYS_BUNDLE.getString("jdbc.password") ; 
	
	private static DbUtil CONN = new DbUtil();
	
	/**
	 * 构造方法私有
	 */
	private DbUtil()
	{
		
	}
	
	public static DbUtil INSTANCE()
	{
		return CONN;
	}
	
	/**
	 * 获取链接
	 * @return
	 */
	public Connection getConnection()
	{
		Connection conn = null ; 
		try
		{
			//加载驱动
			Class.forName(driver);
			//获得链接
			conn = DriverManager.getConnection(url, user, password);
			//操作数据库
			
			//关闭链接
		} catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		return conn ; 
	}
	
	/**
	 * 关闭数据库
	 */
	public void closeAll(Connection conn , Statement stat , ResultSet rs)
	{
		try
		{
			if(rs != null)
			{
				rs.close();
				rs = null ;
			}
			
			if(stat != null)
			{
				stat.close();
				stat = null ;
			}
			
			if(conn != null)
			{
				conn.close();
				conn = null ;
			}
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 测试方法
	 * @param args
	 */
	public static void main(String[] args)
	{
		//测试单例模式
		/*for(int i = 0 ; i < 20 ; i ++)
		{
			DbUtil db = DbUtil.INSTANCE();
			System.out.println(i + "---" + db);
		}*/
		
		/*
		 * 测试链接数据库
		 */
		Connection conn = DbUtil.INSTANCE().getConnection();
		System.out.println(conn);
		DbUtil.INSTANCE().closeAll(conn, null, null);
	}
	
	/**
	 * jdbc的测试方法,备份
	 */
	private static void jdbcHelloWorld()
	{
		String driver = "com.mysql.jdbc.Driver" ;
		String url = "jdbc:mysql://www.wabi.com/test" ; 
		String user = "wabi_cms" ; 
		String password = "wabitebi2012" ; 
		
		Connection conn = null ; 
		try
		{
			//加载驱动
			Class.forName(driver);
			//获得链接
			conn = DriverManager.getConnection(url, user, password);
			//操作数据库
			
			//关闭链接
		} catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		} catch (SQLException e)
		{
			e.printStackTrace();
		}finally
		{
			try
			{
				if(conn != null)
				{
					conn.close();
					conn = null ; 
				}
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
	}
}
